package com.shanjupay.merchant.controller;


import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.PhoneUtil;
import com.shanjupay.merchant.api.MerchantService;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.common.util.SecurityUtil;
import com.shanjupay.merchant.convert.MerchantDetailConvert;
import com.shanjupay.merchant.convert.MerchantRegisterConvert;
import com.shanjupay.merchant.service.FileService;
import com.shanjupay.merchant.service.SmsService;
import com.shanjupay.merchant.vo.MerchantDetailVO;
import com.shanjupay.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author hmk
 */
@Api(value = "商户平台‐商户相关", tags = "商户平台‐商户相关", description = "商户平台‐商户相关")
@RestController
@Slf4j
public class MerchantController {

    //使用dubbo提供的Reference接口 帮我们生成代理对象，使用dubbo协议远程调用服务商户服务，根据id进行查询
    //商户信息
    @Reference
    MerchantService merchantService;

    @Autowired
    SmsService smsService;

    @Autowired
    FileService fileService;
    @ApiOperation("根据id查询用户")
    @GetMapping("/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id){
        //生成的merchantService代理对象就可以使用像调用本地方法一样
        //实现应用层使用dubbo调用该商户微服务（暴露接口）提供的服务
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }


    @ApiOperation("回去登陆用户的商户信息信息")
    @GetMapping("/my/merchants")
    public MerchantDTO getMyMerchantInfo(){
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);
        return merchantDTO;
    }


    /*
     * 获取手机验证码
     *该接口在Application应用提供接口：作用就是该接口调用验证码服务提供的该接口
     *
     * */
    @ApiOperation("获取验证码")
    @ApiImplicitParam(name="phone",value = "手机号",required = true,dataType = "String",paramType = "query")
    @GetMapping("/sms")
    public String  getSMSCode(@RequestParam("phone") String phone){
        log.info("向手机号发送验证码:{}",phone);
        return smsService.sendMsg(phone);
    }

    /*
     * 测试Swagger
     *
     * */
    @ApiOperation("测试")
    @GetMapping(path = "/hello")
    public String hello(){
        return "hello";
    }
    @ApiOperation("测试")
    @ApiImplicitParam(name="name",value = "姓名",required = true,dataType = "string")
    @PostMapping(value = "/hi")
    public String hi(String name){
        return "hi,"+name;
    }


    /*
     * 商户注册
     *1定义vo实体对象 用来接收前端接收注册用户提交数据
     *2商户注册controller接口
     *3商户注册的业务接口实现
     * 3.1前端发送请求给application服务，application接收请求发送请求给验证码服务进行校验验证码
     * 3.2application应用远程调用由商户服务暴露dubbo接口服务进行注册用户
     * */
    /*
    * @param：前端传输过来的注册商户填写的数据
    * @return 注册成功返回商户注册数据
    *
    * */
    @ApiOperation("注册商户")
    @ApiImplicitParam(name="merchantRegister",value = "注册信息",required = true,dataType = "MerchantRegisterVO",paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVO registerVO(@RequestBody MerchantRegisterVO  merchantRegister){

        //测试不可预知异常 系统异常 构造被除数不为0
        //int  i = 1/0;
        //参数校验

        //1校验注册的用户信息MerchantDTO对象不为空
        if(merchantRegister == null){
            throw new BusinessException(CommonErrorCode.E_100108);
        }
        //手机号非空校验
        if(StringUtils.isBlank(merchantRegister.getMobile())){
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        //3手机号合法性校验
        if(!PhoneUtil.isMatches(merchantRegister.getMobile())){
            throw  new BusinessException(CommonErrorCode.E_100109);
        }

        //1校验验证码
        smsService.checkVerifiyCode(merchantRegister.getVerifiykey(),merchantRegister.getVerifiyCode());
        //2注册商户
        //远程调用dubbo接口提供的商户注册服务， 该商户服务提供注册服务传递dto实体对象数据，
        //2.1创建DTO实体对象
        //MerchantDTO merchantDTO = new MerchantDTO();
        //2.2DTO对象填入注册信息
        //merchantDTO.setMobile(merchantRegister.getMobile());
        //merchantDTO.setUsername(merchantRegister.getUsername());
        //vo转化dto
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.voTodto(merchantRegister);

        //.........
        //生成代理对象远程调用该商户服务提供的注册服务
         merchantService.createMerchantDTO(merchantDTO);
        return merchantRegister;

    }

    //上传文件 这里调用本地写的service 上传文件的接口
    @ApiOperation("证件的上传")
    @PostMapping("/upload")
    public String upload(@ApiParam(value = "上传文件",required = true) @RequestParam MultipartFile file) throws IOException {
        //构造一个上传文件名 使用UUID生成的文件名，要上传文件的后缀进行构造
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        //截取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")-1);
        //构造文件名
        String fileName = UUID.randomUUID()+suffix;
        //上次文件同时上传文件返回的上传文件路径（绝对路径）
        return fileService.upload(file.getBytes(),fileName);
    }

    /*资质申请
    * 1写一个用于接收前端的申请信息的vo实体
    * 2写controller接口
    *
    * */
    @ApiOperation("资质申请")
    @PostMapping("/my/merchants/save")
    @ApiImplicitParam(name="merchantInfo",value = "申请认证资料",required = true,dataType = "MerchantDetailVO",paramType = "body")
    public void saveMerchant(@RequestBody MerchantDetailVO merchantInfo){
        //从token中进行获取商户id 资质申请携带该令牌进申请
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.voTodto(merchantInfo);
        System.out.println(merchantId);
       //调用商户提供dubbo接口暴露服务资质申请
        merchantService.applyMerchant(merchantId,merchantDTO);

    }










}
